//
//  WCUserContext.m
//  WeboCon
//
//  Created by black sun on 12-3-3.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "WCUserContext.h"

@implementation WCUserContext
@synthesize accessToken;
@synthesize refreshtoken;
@synthesize expiresin;
@synthesize currentUser;
@synthesize currentUserId;
SYNTHESIZE_SINGLETON_FOR_CLASS(WCUserContext)

-(BOOL)hasLogin{
    //return NO;    
    return self.currentUserId!=nil&&[self.currentUserId intValue]!=0;
}

-(void)instanceDidCreated{
    NSNumber *uid = [WCUserDefaultHelper objectValueForKey:CurrentUidKey];
    self.currentUserId = uid;
}
-(void)saveOldUserData{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *userDefaultKey = nil;
    if (currentUserId!=nil && [currentUserId intValue]!=0) {//如果之前uid不为空，则存储老数据
        userDefaultKey = UserDefaultKeyWithUid(currentUserId);
        NSDictionary *properyDict = [self dictionaryFromUserContextProperties];
        [userDefault setObject:properyDict forKey:userDefaultKey];
    }
    [userDefault synchronize];
}

-(void)setCurrentUserId:(NSNumber *)_currentUserId{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];  
    NSString *userDefaultKey = nil;
    
    currentUserId = _currentUserId;
    
    if (_currentUserId==nil||[_currentUserId intValue]==0) {//新的uid为空，说明要重置用户，将属性置空
        self.accessToken = nil;
        self.refreshtoken = nil;
        self.expiresin = nil;
        self.currentUser = nil;
    }else {//新的uid不为空，则加载数据
        userDefaultKey = UserDefaultKeyWithUid(_currentUserId);
        NSDictionary *propertyDict = [userDefault dictionaryForKey:userDefaultKey];
        if (propertyDict!=nil && propertyDict.count>0) {
            [self setPropertyFromDictionary:propertyDict];
        }else {
            NSDictionary *properyDict = [self dictionaryFromUserContextProperties];
            [userDefault setObject:properyDict forKey:userDefaultKey];
        }
    }
    
    [userDefault setObject:_currentUserId forKey:CurrentUidKey];

    [userDefault synchronize];
    
}


-(NSDictionary *)dictionaryFromUserContextProperties{
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [dictionary setValue:accessToken forKey:YOAuthv2AccessToken];
    [dictionary setValue:refreshtoken forKey:YOAuthv2RefreshToken];
    [dictionary setValue:expiresin forKey:YOAuthv2ExpiresIn];
    [dictionary setValue:currentUserId forKey:OAuthUserIdKey];
    return dictionary;
}
-(void)setPropertyFromDictionary:(NSDictionary *)dict{
    self.accessToken = [dict objectForKey:YOAuthv2AccessToken];
    self.refreshtoken = [dict objectForKey:YOAuthv2RefreshToken];
    self.expiresin = [dict objectForKey:YOAuthv2ExpiresIn];
}

@end
